<template>
  <div class="package-basic">
    <el-form ref="classRoomForm" :model="Classroom" label-width="220px" :rules="rules">
      <el-form-item label="课程包分类选择" prop="categoryId">
        <treeselect
          v-model="Classroom.categoryId"
          :multiple="false"
          :options="courseCategorys"
          style="width: 200px"
        />
      </el-form-item>
      <el-form-item label="课程包名称" prop="title">
        <el-input v-model="Classroom.title"/>
      </el-form-item>
      <el-form-item label="学员选择" prop="student">
        <el-button type="primary" plain @click="studentDialog = true">添加学员</el-button>
        <div v-show="Classroom.students.length>0" class="tagBox">
          <el-tag v-for="(tag,index) in Classroom.students" :key="tag.name" closable @close="deleleTag(index)">{{tag.name}}</el-tag>
        </div>
      </el-form-item>
      <el-form-item label="定价" prop="price">
        <el-input v-model="Classroom.price" placeholder="0.00"/>
      </el-form-item>
      <el-form-item label="班级类型">
        <el-radio v-model="Classroom.type" label="1">普通班级</el-radio>
        <el-radio v-model="Classroom.type" label="2">培训计划</el-radio>
      </el-form-item>
      <el-form-item label="课程包有效期">
        <el-radio v-model="Classroom.expiryMode" label="1">固定天数</el-radio>
        <el-radio v-model="Classroom.expiryMode" label="2">固定日期</el-radio>
        <el-radio v-model="Classroom.expiryMode" label="3">无限期</el-radio>
        <p v-if="Classroom.expiryMode === 1" style="color:#8a8a8a;margin: 10px 0 0;">
          有效天数
          <el-input-number
            v-model="Classroom.expiryValue"
            :min="1"
            :max="100"
            style="margin-left:10px;"
          />
        </p>
        <p v-if="Classroom.expiryMode === 2" style="color:#8a8a8a;margin: 10px 0 0;">
          有效日期
          <el-date-picker
            v-model="Classroom.expiryValue"
            type="daterange"
            range-separator="|"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="margin-left:10px;"
          />
        </p>
      </el-form-item>
      <el-form-item label="课程包封面">
        <img
          v-if="Classroom.largePicture"
          :src="Classroom.largePicture"
          alt
          class="img"
          style="width:270px;height:auto;"
        />
        <el-upload
          :on-change="handleChange"
          :http-request="uploadFile"
          :limit="1"
          action=""
          class="upload-demo"
          accept="image/jpg, image/png"
        >
          <el-button slot="trigger" size="small" type="primary">点击上传</el-button>
        </el-upload>
      </el-form-item>
      <el-form-item label="课程包简介">
        <el-input
          v-model="Classroom.about"
          :rows="6"
          type="textarea"
          placeholder="输入课程描述"
          style="width:500px;"
        />
        <p style="margin:0;color:#8a8a8a">注:课程包简介最多输入120个字</p>
      </el-form-item>
      <el-form-item label="课程包详情">
        <div style="width:580px;">
          <tinymce :toolbar="Classroom.toolbar" :height="250" :show="true"/>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="nextStep">保存并继续</el-button>
        <el-button type="primary" @click="nextStepOnly">下一步</el-button>
        <el-button @click="studentHandleCancel">取消</el-button>
      </el-form-item>
    </el-form>
    <el-dialog title="选择学员" :visible.sync="studentDialog" width="750px">
      <el-row>
        <el-input
          v-model="studentName"
          clearable
          placeholder="请输入员工名称或关键字"
          style="width:200px;"
          @clear="studentFilterTable = studentData"
          @keyup.enter.native="searchStudent"
        ></el-input>
        <el-button type="primary" @click="searchStudent">搜 索</el-button>
      </el-row>
      <el-table
        type="selection"
        ref="multipleTable"
        :data="studentFilterTable.slice(
        (listQuery.page - 1) * listQuery.limit,
        listQuery.page * listQuery.limit
      )"
        tooltip-effect="dark"
        :row-key="getRowKey"
        style="width: 100%"
        @selection-change="studentHandleSelectionChange"
      >
        <el-table-column type="selection" :reserve-selection="true" width="55"></el-table-column>
        <el-table-column prop="name" label="姓名"></el-table-column>
      </el-table>
      <pagination
        :limit.sync="listQuery.limit"
        :page.sync="listQuery.page"
        :total="total"
        @handleCurrentChange="studentHandleCurrentChange"
        @handleSizeChange="handleSizeChange"
        v-show="total>0"
      />
      <span slot="footer" class="dialog-footer">
        <el-button @click="studentHandleCancel">取 消</el-button>
        <el-button type="primary" @click="studentHandleConfirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  // import the component
  import Treeselect from '@riophae/vue-treeselect'
  // import the styles
  import '@riophae/vue-treeselect/dist/vue-treeselect.css'
  import { categoryList, getStudentList } from '@/api/user/user' // 数据接口 // 数据接口
  import { getClassroomDetail, saveClassRoom } from '@/api/subject/classroom' // 数据接口
  import { getTenantId } from '@/utils/auth'
  import Tinymce from '@/components/Tinymce'
  import imgDialog from './packagedetail/dialog'
  import { pushMessageBus } from './eventbus'
  import { upLoadFile } from '@/api/upLoadFile' // 数据接口
  import Pagination from '@/components/Pagination' // 分页组件

  export default {
    components: {
      Tinymce,
      imgDialog,
      Treeselect,
      Pagination
    },
    data() {
      return {
        Classroom: {
          categoryId: null,
          title: '',
          price: '',
          students: [],
          studentIds: '',
          expiryMode: '',
          expiryValue: '',
          largePicture:
            ''
        },
        courseCategorys: [],
        total: 0,
        rules: {
          categoryId: [
            { required: true, message: '请选择分类', trigger: 'blur' }
          ],
          title: [
            { required: true, message: '课程包名称不能为空', trigger: 'blur' }
          ],
          price: [{ required: true, message: '价格不能为空', trigger: 'blur' }]
        },
        // 保存选中的数据id,row-key就是要指定一个key标识这一行的数据
        getRowKey(row) {
          return row.id
        },
        dialog: false,
        filterTable: [],
        tableData: [],
        multipleSelection: [],
        listQuery: {
          nickName: '',
          tenantId: getTenantId(),
          page: 1,
          limit: 20
        },
        studentDialog: false,
        studentName: '',
        studentData: [],
        studentFilterTable: [],
        studentMultipleSelection: []
      }
    },
    mounted() {
      this.getClassRoomData()
      this.getCourseCategorys()
      // 接收来自upload组件的select动作
      pushMessageBus.$on('fromUpload-selected', value => {
        this.form.waitUrl = value.url
        this.dialog = false
      })
      // 接收来自history组件的select动作
      pushMessageBus.$on('fromHistory-selected', value => {
        this.form.waitUrl = value.url
        this.dialog = false
      })
      this.filterTable = this.tableData
    },
    methods: {
      nextStep() {
        this.saveClassRoom()
      },
      nextStepOnly() {
        this.$emit('goNext', this.Classroom.id)
      },
      studentHandleCancel() {
        this.studentClearDialog()
      },
      // 改变分页页数
      handleSizeChange(val) {
        this.listQuery.page = 1
        this.listQuery.limit = val.value
        this.getStudentListData()
      },
      studentHandleCurrentChange(val) {
        this.listQuery.page = val.value
        this.getStudentListData()
      },
      getCourseCategorys() {
        categoryList('class', getTenantId())
          .then(response => {
            this.courseCategorys = response.data.items
          })
          .catch(() => {
          })
      },
      getStudentListData() {
        getStudentList(getTenantId()).then(response => {
          this.studentData = response.data.items
          this.studentFilterTable = response.data.items
          this.total = response.data.total

          this.studentData.map(item => {
            if (this.Classroom.studentIds) {
              if (this.Classroom.studentIds.match(item.id)) {
                //包含；
                this.Classroom.students.push({
                  id: item.id,
                  name: item.name
                })
              }
            }
          })
        })
      },
      saveClassRoom() {
        this.$refs['classRoomForm'].validate(valid => {
          if (valid) {
            if (!this.Classroom.categoryId) {
              this.$message.error('请选择分类!')
            } else {
              this.Classroom.tenantId = getTenantId()
              if (this.Classroom.students) {
                let a = []
                this.Classroom.students.forEach((item) => {
                  a.push(item.id)
                })
                this.Classroom.studentIds = a.join(',')
              }
              delete this.Classroom.students
              saveClassRoom(this.Classroom).then(res => {
                this.Classroom = {}
                this.$notify({
                  title: '成功',
                  message: '创建成功',
                  type: 'success',
                  duration: 2000
                })
                this.$emit('goNext', res.data.items)
              })
            }
          }
        })
      },
      getClassRoomData() {
        if (this.$route.params.ID) {
          getClassroomDetail(this.$route.params.ID).then(response => {
            this.Classroom = response.data.eduxcloudClassroom
            this.Classroom.students = []
            console.log('categoryId:' + this.Classroom.categoryId)
            if (this.Classroom.categoryId === 0) {
              this.Classroom.categoryId = null
            }
          })
        }
        this.getStudentListData()
      },
      handleChange(file) {
        this.file = file.raw
      },
      uploadFile() {
        const fileForm = new FormData()
        fileForm.append('name', this.file.name)
        fileForm.append('uid', this.file.uid)
        fileForm.append('file', this.file)
        upLoadFile(fileForm).then(response => {
          this.Classroom.largePicture = response.data.url
        })
      },
      backStep() {
        this.$emit('back')
      },
      handleClose() {
        this.dialog = false
      },
      studentHandleSelectionChange(val) {
        this.studentMultipleSelection = val
      },
      studentHandleConfirm() {
        if (this.studentMultipleSelection.length < 1) {
          this.$message.warning('请选择学员')
          return
        }
        this.Classroom.students.push(...this.studentMultipleSelection)
        this.studentClearDialog()
      },
      studentClearDialog() {
        this.studentDialog = false
        this.$refs.multipleTable.clearSelection()
        this.studentMultipleSelection = []
      },
      searchStudent() {
        // 如果有选择教师先清空多选数据
        this.$refs.multipleTable.clearSelection()
        this.studentMultipleSelection = []
        var search = this.studentName
        if (search) {
          this.studentFilterTable = this.studentData.filter(function(dataNews) {
            return Object.keys(dataNews).some(function(key) {
              return ~String(dataNews[key])
                .toLowerCase()
                .indexOf(search)
            })
          })
        } else {
          this.studentFilterTable = this.studentData
        }
      },
      deleleTag(index) {
        this.Classroom.teachers.splice(index, 1)
        console.log(this.Classroom.teachers)
      }
    }
  }
</script>

<style lang="scss" scoped>
  .package-basic {
    .el-form {
      margin-top: 30px;

      .el-input {
        width: 200px;
      }

      .el-select {
        width: 130px;
      }
    }

    .tagBox {
      width: 300px;

      .el-tag {
        margin-right: 10px;
      }
    }
  }
</style>


